package com.seo.main;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.PostConstruct;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;

import com.google.common.base.Predicate;
import com.google.common.base.Predicates;

import springfox.documentation.RequestHandler;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
@Profile({ "local", "dev", "test" })
public class Swagger2Config {

	private List<String> basePackage;
	private List<String> urlList;

	@PostConstruct
	public void init() {
		basePackage = new ArrayList<>();
		basePackage.add("com.seo.controller.user");
		basePackage.add("com.seo.controller.index");
		urlList = new ArrayList<>();
		urlList.add("/code.*");
		urlList.add("/login.*");

		urlList.add("/swaggerTest.*");
	}

	@Bean
	public Docket createRestApi() {
		return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).select().apis(basePackage(basePackage))
				.paths(paths()).build();
	}

	private ApiInfo apiInfo() {
		return new ApiInfoBuilder().title("测试Swagger2").description("欢迎到我的API")
				.termsOfServiceUrl("https://www.baidu.com")
				.contact(new Contact("小黑", "www.baidu.com", "88888888@163.com")).version("1.0").build();
	}

	public Predicate<RequestHandler> basePackage(final List<String> basePackage) {
		return new Predicate<RequestHandler>() {
			@Override
			public boolean apply(RequestHandler input) {
				return basePackage.contains(declaringClass(input).getPackage().getName());
			}
		};
	}

	private Class<?> declaringClass(RequestHandler input) {
		return input.getHandlerMethod().getMethod().getDeclaringClass();
	}

	private Predicate<String> paths() {
		String urlStr = "";
		if (urlList.size() > 0) {
			for (String s : urlList) {
				urlStr = urlStr + s + "|";
			}
			urlStr = urlStr.substring(0, urlStr.length() - 1);
			return Predicates.or(PathSelectors.regex(urlStr));
		} else {
			return PathSelectors.any();
		}

	}
}
